package com.ccit.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccit.common.exception.GymException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.PageUtil;
import com.ccit.common.utils.RedisUtils;
import com.ccit.common.utils.TimeFormatter;
import com.ccit.model.Employee;
import com.ccit.model.User;
import com.ccit.model.vo.employee.EmployeeVo;
import com.ccit.model.vo.member.MemberVo;
import com.ccit.user.service.UserService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Api(tags = "会员账号管理")
@RestController
@EnableScheduling
@RequestMapping("/user/member")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisUtils redisUtils;


    @HystrixCommand(fallbackMethod = "getMsgFallback")
    @ApiOperation(value = "分页查询会员信息")
    @GetMapping("/findPage/{current}/{limit}")
    public Result getUserByPage(@PathVariable("current") Integer current,
                                @PathVariable("limit") Integer limit) {
            Page<User> userPage = new Page<>(current, limit);
            QueryWrapper<User> wrapper = new QueryWrapper<User>();
            wrapper.lambda()
                    .orderByDesc(User::getCreateTime);
            Page<User> page = userService.page(userPage, wrapper);
        return Result.ok(page);
    }

    @ApiOperation(value = "添加新的会员信息")
    @PostMapping("/saveUser")
    public Result addUser(@RequestBody MemberVo memberVo) {
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("phone", memberVo.getPhone());
        List<User> list = userService.list(wrapper);
        if (list.size() > 0) {
            throw new GymException(213, "手机号已使用");
        }
        //格式化时间戳
        String time = TimeFormatter.getCurrentTime();
        Integer month = memberVo.getMonth();
        Date date = TimeFormatter.getAfterMonth(time, month);
        Timestamp invalidTime = new Timestamp(date.getTime());
        //封装会员数据
        User user = new User();
        user.setName(memberVo.getName());
        if (memberVo.getCoach() != "")
            user.setCoach(memberVo.getCoach());
        user.setPhone(memberVo.getPhone());
        user.setType(memberVo.getType());
        user.setPrice(memberVo.getPrice());
        user.setCreateTime(new Timestamp(new Date().getTime()));
        user.setInvalidTime(invalidTime);

        System.out.println(user.getCoach());
        boolean result = userService.save(user);
        if (result) {
            return Result.ok("添加成功");
        } else {
            return Result.fail("添加失败");
        }
    }

    @ApiOperation(value = "根据id删除会员信息")
    @DeleteMapping("/removeUser/{id}")
    public Result removeUser(@PathVariable("id") int id) {
        boolean flag = userService.removeById(id);
        if (flag){
            return Result.ok("删除成功");
        }
        else
            return Result.fail("删除出错啦");
    }


    @ApiOperation(value = "根据手机号条件精准查询")
    @GetMapping("/findByPhone/{phone}")
    public Result getUserByPhone(@PathVariable("phone") String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        wrapper.orderByDesc("create_time");
        //调用方法实现分页查询
        List<User> list = userService.list(wrapper);
        if (list.size()==0){
            throw new GymException(202,"查无此手机号会员");
        }
        System.out.println(list+"================");
        return Result.ok(list);

    }

    @ApiOperation(value = "根据id更改会员绑定手机号")
    @PutMapping("/updateUserPhone/{id}/{phone}")
    public Result updateUserPhone(@PathVariable("id") Integer id,
                                  @PathVariable("phone") String phone) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        queryWrapper.orderByDesc("create_time");
        List<User> list = userService.list(queryWrapper);
        if (list.size() > 0) {
            //当手机号已存在
            throw new GymException(213, "手机号已使用");
        }
        UpdateWrapper<User> wrapper = new UpdateWrapper();
        wrapper.eq("id", id);
        wrapper.set("phone", phone);
        boolean flag = userService.update(wrapper);
        if (flag) {
            return Result.ok();
        } else {
            return Result.fail("更新失败");
        }
    }

    @ApiOperation(value = "查询是否为会员")
    @GetMapping("/judgeMemberOrNot/{phone}")
    public Result judgeMember(@PathVariable String phone) {
        int count = userService.count(new QueryWrapper<User>().eq("phone", phone));
        if (count > 0)
            //存在该会员
            return Result.ok(true);
        else
            return Result.ok(false);
    }

    @ApiOperation("定期删除过期会员")
    @Scheduled(cron = "0 0 */1 * * ?")
    @DeleteMapping("/remove")
    public Result removeMember() {
        //批量模糊删除所有包含keys的数据
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .le(User::getInvalidTime, format)
                .orderByDesc(User::getCreateTime);
        List<User> list = userService.list(wrapper);
        if (list != null) {
            boolean remove = userService.remove(wrapper);
            if (remove) {
                return Result.ok("删除成功");
            } else return Result.fail().message("删除失败");
        } else return Result.ok("无过期人员");
    }


    @ApiOperation("修改会员信息")
    @PutMapping("/updateInfo")
    public Result updateUserInfo(@RequestBody MemberVo memberVo) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", memberVo.getId());
        User upUser = userService.getOne(queryWrapper);
        if (upUser != null) {
            upUser.setPhone(memberVo.getPhone());
            upUser.setName(memberVo.getName());
            upUser.setCoach(memberVo.getCoach());
            boolean flag = userService.updateById(upUser);
            if (flag){
                return Result.ok("修改成功");
            }
            else
                throw new GymException(501, "修改失败");
        } else {
            throw new GymException(502, "查无此会员");
        }
    }

    public Result getMsgFallback(Integer current,
                                 Integer limit) {
        return Result.ok("服务熔断");
    }

    }
